package com.wolfking.back.core.service;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.common.collect.Sets;
import com.wolfking.back.core.bean.Menu;
import com.wolfking.back.core.bean.User;
import com.wolfking.back.core.feignclient.SsoFeignClient;
import com.wolfking.back.core.util.CookieUtil;

/**
 * 用户单点登录的service
 * 
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月23日 下午4:58:50
 * @copyright wolfking
 */
@Service
public class SsoUserService {

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private SsoFeignClient ssoFeignClient;

	/**
	 * 获取用户登录的tokenId
	 * 
	 * @param request
	 * @return
	 */
	public String getTokenId(HttpServletRequest request) {
		return CookieUtil.getCookie(request, "tokenId");
	}

	/**
	 * 根据tokenid 获取user
	 * 
	 * @param tokenId
	 * @return
	 */
	public User getTokenUser(String tokenId) {
		try {
			ResponseEntity<User> entity = ssoFeignClient.checkLogin(tokenId);
			User user = entity.getBody();
			return user;
		} catch (Exception e) {
			logger.error("get token user error", e);
			return null;
		}
	}

	/**
	 * 获取当前的用户
	 * 
	 * @return
	 */
	public User getUser() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String tokenId = getTokenId(request);
		if (StringUtils.isNotBlank(tokenId))
			return getTokenUser(tokenId);
		else
			return null;
	}

	/**
	 * 获取用户有权限的菜单
	 * 
	 * @return
	 */
	public List<Menu> getUserMenus(String userId) {
		return ssoFeignClient.getUserMenus(userId).getBody();
	}

	/**
	 * 获取用户所有的鉴权码
	 * 
	 * @param userId
	 * @return
	 */
	public Set<String> getUserAuthCodes(String userId) {
		try {
			return ssoFeignClient.getUserAuthCodes(userId).getBody();
		} catch (Exception e) {
			logger.error("get getUserAuthCodes error", e);
			return Sets.newHashSet();
		}
	}
}
